package com.guyu.plugin.sms;

import cn.hutool.core.collection.CollectionUtil;
import com.guyu.common.web.util.GuyuSpringUtils;
import com.guyu.plugin.sms.core.GuyuBlackListDao;
import com.guyu.plugin.sms.core.GuyuBlackListProcessor;
import com.guyu.plugin.sms.core.GuyuSmsDao;
import com.guyu.plugin.sms.suoyou.config.SuoyouFactory;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.dromara.sms4j.api.dao.SmsDao;
import org.dromara.sms4j.api.proxy.SmsProcessor;
import org.dromara.sms4j.core.proxy.SmsProxyFactory;
import org.dromara.sms4j.core.proxy.processor.BlackListProcessor;
import org.dromara.sms4j.core.proxy.processor.BlackListRecordingProcessor;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;

import java.util.LinkedList;

@Slf4j
@AutoConfiguration
public class SmsAutoConfiguration {
    @Bean
    public SuoyouFactory suoyouSmsFactory() {
        return SuoyouFactory.instance();
    }

    @Bean
    public SmsDao smsDao() {
        return new GuyuSmsDao();
    }


    @PostConstruct
    public void init() {
        LinkedList<SmsProcessor> processors = SmsProxyFactory.getProcessors();
        if (CollectionUtil.isNotEmpty(processors)) {
            processors.forEach(processor -> {
                if (processor instanceof BlackListProcessor) {
                    SmsProxyFactory.removePreProcessor(processor);
                } else if (processor instanceof BlackListRecordingProcessor) {
                    SmsProxyFactory.removePreProcessor(processor);
                }
            });
        }
        SmsProxyFactory.addPreProcessor(new GuyuBlackListProcessor(getGuyuBlackListDao()));
    }


    private GuyuBlackListDao getGuyuBlackListDao() {
        try {
            return GuyuSpringUtils.getBean(GuyuBlackListDao.class);
        } catch (Exception e) {
            log.warn("尝试加载GuyuBlackListDao失败");
        }
        return null;
    }
}
